package com.lute.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.ide.eclipse.quickfix.jdt.processors.RequestMappingDialog.Method;
import org.springframework.security.oauth2.common.json.JSONException;
import org.springframework.security.oauth2.common.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lute.model.Approver;
import com.lute.model.ClientAccountingPeriodState;
import com.lute.model.ClientAdmin;
import com.lute.model.Employee;
import com.lute.model.EmployeeAccountingPeriod;
import com.lute.model.EmployeeAccountingPeriodState;
import com.lute.model.User;
import com.lute.model.UserEntitlement;
import com.lute.utils.ServerErrorResponse;

@Controller
public class AccountingPeriodCheckedServlet {
	
	@RequestMapping (value="/markAsChecked",method= RequestMethod.POST, headers = "Content-type=application/json")
	public @ResponseBody String accountingPeriodChecked(@RequestBody String dataJSON, HttpServletRequest request) throws JSONException {
		String result = "";
		String userIdStr;
		String from;
		JSONObject jsonReq;
		JSONObject jsonRes =  new JSONObject();
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_LOGGED_IN.toString());
			result = jsonRes.toString();
			return result;
		}
		
		try {
			jsonReq = new JSONObject(dataJSON);
			userIdStr = jsonReq.getString("userId");
			from = jsonReq.getString("from");
		} catch(JSONException e) {
			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			return result;
		}
		
		/* check if json data was not malformed */
		if( (jsonReq.isNull("userId")) && (jsonReq.isNull("from")) ) {
			jsonRes.put("result",ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			System.out.println(result);
			return result;
		}
		
		String role = (String)session.getAttribute("role");
		
		/* check  authorization */
		if(!((role.equals("approver")) || (role.equals("clientAdmin")))) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
			result = jsonRes.toString();
			System.out.println(result);
			return result;
		}
		
		int sessionUserId = (Integer)session.getAttribute("sessionUserId");
		int userId = Integer.parseInt(userIdStr);
		jsonRes.put("result", "");
		
		EmployeeAccountingPeriod employeeAccountingPeriod = null;
		
		try {
			
			employeeAccountingPeriod = UserEntitlement.checkUserPrivilegeToEmployeeAccountingPeriod(from,sessionUserId,userId,role,jsonRes);
			
			if(!(jsonRes.get("result").equals(""))) {
				result = jsonRes.toString();
				System.out.println(result);
				return result;
			}
			
			if(employeeAccountingPeriod == null) {
				jsonRes.put("result", ServerErrorResponse.UNKNOWN_ACCOUNTING_PERIOD.toString());
				result = jsonRes.toString();
				return result;
			}
			
			EmployeeAccountingPeriod.doAccountingPeriodVerification(employeeAccountingPeriod, jsonRes);
		    
		    if(!(jsonRes.get("result").equals(""))) {
				result = jsonRes.toString();
				System.out.println(result);
				return result;
			}
			
			if((employeeAccountingPeriod.getClientAccountingPeriod().getClientAccountingPeriodState()
					.equals(ClientAccountingPeriodState.CLOSE.toString()))) {
				jsonRes.put("result", ServerErrorResponse.ACCOUNTING_PERIOD_ALREADY_CLOSED.toString());
				result = jsonRes.toString();
				return result;
			}
			
			if(role.equals("approver")) {
				if(sessionUserId == userId) {
					if(employeeAccountingPeriod.getEmployeeAccountingPeriodState().equals(EmployeeAccountingPeriodState.CHECKED_BY_APPROVER.toString())) {
						jsonRes.put("result", ServerErrorResponse.OPERATION_NOT_ALLOWED.toString());
						result = jsonRes.toString();
						System.out.println(result);
						return result;
					}
					/* Approver want to check his own calendar ? */
					employeeAccountingPeriod.setEmployeeAccountingPeriodState(EmployeeAccountingPeriodState.CHECKED_BY_APPROVER.toString());
				} else {
					if(employeeAccountingPeriod.getEmployeeAccountingPeriodState().equals(EmployeeAccountingPeriodState.SENT_TO_APPROVER.toString())) {
						employeeAccountingPeriod.setEmployeeAccountingPeriodState(EmployeeAccountingPeriodState.CHECKED_BY_APPROVER.toString());
					} else {
						jsonRes.put("result", ServerErrorResponse.OPERATION_NOT_ALLOWED.toString());
						result = jsonRes.toString();
						System.out.println(result);
						return result;
					}
				}
			} else {
				if(employeeAccountingPeriod.getEmployeeAccountingPeriodState().equals(EmployeeAccountingPeriodState.CHECKED_BY_CLIENT_ADMIN.toString())) {
					jsonRes.put("result", ServerErrorResponse.OPERATION_NOT_ALLOWED.toString());
					result = jsonRes.toString();
					System.out.println(result);
					return result;
				}
				if(employeeAccountingPeriod.getEmployeeAccountingPeriodState().equals(EmployeeAccountingPeriodState.SENT_TO_CLIENT_ADMIN.toString())) {
					employeeAccountingPeriod.setEmployeeAccountingPeriodState(EmployeeAccountingPeriodState.CHECKED_BY_CLIENT_ADMIN.toString());
				} else {
					jsonRes.put("result", ServerErrorResponse.OPERATION_NOT_ALLOWED.toString());
					result = jsonRes.toString();
					System.out.println(result);
					return result;
				}
			}
			
			EmployeeAccountingPeriod.updateEmployeeAccountingPeriodInDB(employeeAccountingPeriod);
			
		} catch(NullPointerException npe){
			jsonRes.put("result", ServerErrorResponse.INTERNAL_ERROR.toString());
			result = jsonRes.toString();
			System.out.println(result);
			return result;
		}
		jsonRes.put("result","OK");
		jsonRes.put("newEmployeeAccountingPeriodState", employeeAccountingPeriod.getEmployeeAccountingPeriodState());
		result = jsonRes.toString();
		return result;
	}
}
